<template>
  <div class="share-index-page">
    <topBar style="zIndex:2004;position: relative;">
      <template v-slot:left>
        <div class="logo-img" :class="[brevity && 'small-img']">
          <!-- <img :src="logoImg" @click="goHome()"> -->
          <div class="logo-image" :style="{ backgroundImage: `url(${logoImg})` }" @click="goHome()"></div>
        </div>
      </template>
    </topBar>
    <div class="share-view-file-box" id="view-file-box" ref="viewFileRef" v-loading="sahreLoading"
      :style="{ width: (showMenuBut || !['document_html', 'md'].includes(docInfo.type)) ? '100%' : 'calc(100% - 268px)' }">
      <dirShare ref="fileViewShowRef" :docInfo="docInfo" @renderFinish="renderFinish" v-if="docInfo.type == 'directory'">
      </dirShare>
      <el-scrollbar ref="viewFileScroll" @scroll="bodyScroll" v-else :style="{
        paddingRight: docInfo.type == 'document_html' ? '16px' : '0px'
      }">
        <fileViewShow ref="fileViewShowRef" :formShare="true" :docInfo="docInfo"
          @refreshScrollState="refreshScrollState" @setMenuList="setMenuList" @renderFinish="renderFinish">
        </fileViewShow>
      </el-scrollbar>
    </div>
    <div class="knowledge-other" v-if="docInfo.type != 'directory'">
      <menuLists v-show="!showMenuBut && menuList.length != 0" v-if="['document_html', 'md'].includes(docInfo.type)"
        ref="menuListRef" :menuList="menuList" @close="changeMenuStatus" @clickScroll="scrollNode" :show="!showMenuBut">
      </menuLists>
    </div>
    <div class="menu-button-box"
      v-if="docInfo.type != 'directory' && showMenuBut && ['document_html', 'md'].includes(docInfo.type)"
      @click="changeMenuStatus">
      <svg class="menu-icon">
        <use xlink:href="#keowledge-a-zu7044"></use>
      </svg>
    </div>
    <el-dialog v-model="pwdVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="377px"
      :show-close="false" modal-class="dialog-center pwd-modal" class="custom-dialog">
      <div class="share-pwd-box">
        <div class="share-title-box">
          <img :src="docInfo.headImg ? docInfo.headImg : userImg">
          <span>{{ docInfo.createBy }}{{ $t('message.text.encryPasswordFiles') }}</span>
        </div>
        <div class="share-pwd-input">
          <div class="ple-t">{{ $t('message.placeholder.pleasePassword') }}</div>
          <div class="input-box">
            <el-input v-model="pwdInput" @keydown.enter="checkPwd"></el-input>
            <el-button class="button" type="primary" @click="checkPwd">{{ $t('message.buttons.submit') }}</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  toRefs,
  watch,
  onMounted,
  getCurrentInstance,
  unref,
  computed
} from 'vue'
import type { ComponentInternalInstance } from 'vue'
import userImg from '@/assets/common/user.png'
import topBar from '@/views/topBar/topBar.vue'
import fileViewShow from '@/views/common/fileView.vue'
import dirShare from './dirShare.vue'
import menuLists from '@/views/common/menuList.vue'
import { useRoute, useRouter, userRoute } from "vue-router"
import useUserInfoStore from '@/store/userInfo';
import { checkShare, getInfo, getSharParams } from '@/api/common'
import { urlParsParams, encryption } from '@/utils/util'
import { enCodeKey } from "@/const/const"
import { useHookI18n } from '@/hooks/i18n'
const { locale, $t } = useHookI18n()
const userInfo = useUserInfoStore()
const router = useRouter();
const route = useRoute()
const emit = defineEmits([""])
const viewFileRef = ref()
const bodyScrollTop = ref(0)
const viewFileScroll = ref()
const fileViewShowRef = ref()
const cliclMenuScroll = ref(false)
const props = defineProps({
})
const originNodeList = ref([])
const menuListRef = ref()
const showMenuBut = ref(false)
const menuList = ref([])
const inputFocus = ref(false)
const pwdInput = ref()
const logoImg = computed(() => {
  return userInfo.tenantInfo?.logo
}
)
const pwdVisible = ref(false)
const sahreLoading = ref(false)
const shareKey = ref<string>('')
const instance: any = getCurrentInstance() as ComponentInternalInstance;
const proxy: any = instance.proxy as any; // 访问 proxy 属性
interface shareParams {
  docId?: string,
  key?: string,
  knId?: string,
  nameSuffix?: string,
  security: string,
  type?: string
}
const shareParams = ref<shareParams>()
const docInfo = ref({})
onMounted(() => {
  sahreLoading.value = true
  shareKey.value = route.params.shareKey
  init()
})
function init() {
  if (shareKey.value) {
    getSharParams(shareKey.value).then(res => {
      if (res.data.code == 0) {
        shareParams.value = urlParsParams(res.data.data)
        getShreCheckInfo()
      }
    })
  } else {
    shareParams.value = route.query
    getShreCheckInfo()
  }
}
function getShreCheckInfo() {
  if (shareParams.value?.key) {
    checkShare({
      key: shareParams.value.key
    }).then(res => {
      if (res.data.code == 0) {
        if (res.data.data.shareStatus) {
          docInfo.value.headImg = res.data.data.headImg
          if (res.data.data.needPwd) {
            pwdVisible.value = true
          } else {
            docInfo.value = res.data.data.dcLibrary
            pwdVisible.value = false
          }
        } else {
          // 分享时间失效
          goHome()
        }
      }
    })
  }
}
function renderFinish() {
  sahreLoading.value = false
}
function bodyScroll({ scrollTop, scrollLeft }) {
  bodyScrollTop.value = scrollTop
  if (cliclMenuScroll.value) return
  if (docInfo.value.type == 'document_html') {
    let lastId = ''
    originNodeList.value.forEach((item, index) => {
      if (item.innerHTML != '<br>') {
        if (['H1', 'H2'].indexOf(item.nodeName) > -1 && item.offsetTop - bodyScrollTop.value <= 14) {
          lastId = item.id
        }
      }

    })
    if (lastId) {
      unref(menuListRef)?.setCurrentKey(lastId)
    }
  } else if (docInfo.value.type == 'md') {
    let lastId = ''
    originNodeList.value.forEach((item, index) => {
      if (document.getElementById(`h${item.level}-${item.id}`) && document.getElementById(`h${item.level}-${item.id}`).offsetTop - bodyScrollTop.value <= 14) {
        lastId = item.id
      }

    })
    if (lastId) {
      unref(menuListRef)?.setCurrentKey(lastId)
    }
  }
}
function setMenuList(val, nodeList) {
  showMenuBut.value = false
  if (val.length != 0 && JSON.stringify(val) != '{}') {
    menuList.value = val
  } else {
    menuList.value = []
  }
  originNodeList.value = nodeList || []
  setTimeout(() => {
    viewFileScroll.value.update()
  }, 200)
}
function refreshScrollState() {
  setTimeout(() => {
    viewFileScroll.value.update()
  }, 100)
}
function checkPwd() {
  let temp = encryption({
    data: { pass: pwdInput.value },
    key: enCodeKey,
    param: ["pass"]
  });
  checkShare({
    key: shareParams.value.key,
    pwd: temp.pass,
  }).then(res => {
    if (res.data.code == 0) {
      if (res.data.data.check) {
        docInfo.value = res.data.data.dcLibrary
        pwdVisible.value = false
      } else {
        proxy.$onePrompt.$oneNotify({
          type: "error",
          message: $t('message.message.passwordError'),
          title: $t('message.prompt'),
          position: 'bottom-right'
        })
      }
    }
  })
}
function goHome() {
  router.push({
    path: '/index'
  })
}
function scrollNode(node) {
  cliclMenuScroll.value = true
  // 编辑页布局更改后不需要减掉页面顶部偏移量
  // viewFileScroll.value.setScrollTop(node.offsetTop - 118)
  if (docInfo.value.type == 'document_html') {
    viewFileScroll.value.setScrollTop(document.getElementById(node.id).offsetTop)
  } else if (docInfo.value.type == 'md') {
    viewFileScroll.value.setScrollTop(document.getElementById(node.nodeName + '-' + node.id).offsetTop)
  }
  setTimeout(() => {
    cliclMenuScroll.value = false
  }, 100)
}
function changeMenuStatus() {
  if (showMenuBut.value) {
    showMenuBut.value = false
  } else {
    showMenuBut.value = true
  }
}
</script>
<style lang="scss" scoped>
.share-index-page {
  height: 100%;
  width: 100%;
  position: relative;

  .logo-img {
    height: 49px;
    width: 200px;
    display: flex;
    align-items: center;
    overflow: hidden;
    padding-right: 12px;
    cursor: pointer;

    img {
      width: 100%;
    }

    .logo-image {
      display: block;
      width: 200px;
      height: 50px;
      overflow: hidden;
      cursor: pointer;
      background-size: contain;
      background-repeat: no-repeat;
      background-position: 50%;
    }
  }

  .share-view-file-box {
    position: relative;
    height: calc(100vh - 70px);

    ::v-deep(.empty-box) {
      min-height: calc(100vh - 70px);
    }
  }

  .knowledge-other {
    position: fixed;
    right: 0px;
    height: calc(100vh - 68px);
    max-width: 268px;
    z-index: 6;
    top: 68px;
  }

  .menu-box {
    height: auto;
  }

  .menu-button-box {
    position: fixed;
    width: 36px;
    height: 36px;
    background: #F5F6F7;
    border-radius: 6px 0px 0px 6px;
    right: 0px;
    top: 150px;
    z-index: 199;
    cursor: pointer;

    .menu-icon {
      width: 36px;
      height: 36px;
      cursor: pointer;
    }
  }
}
</style>
<style lang="scss">
.pwd-modal {
  background: linear-gradient(136deg, rgba(255, 255, 255, 0.29) 0%, rgba(255, 255, 255, 0.46) 96%);
}

.share-pwd-box {
  .share-title-box {
    display: flex;
    align-items: center;
    padding: 0px 32px;
    height: 80px;
    background-image: url('../../assets/images/share-title.png');
    background-size: 100% 100%;

    img {
      width: 40px;
      height: 40px;
      border-radius: 4px;
      overflow: hidden;
      margin-right: 16px;
    }
  }

  .share-pwd-input {
    padding: 0px 40px;
    height: 124px;
    display: flex;
    justify-content: center;
    flex-direction: column;

    .ple-t {
      font-size: 14px;
      @include SourceHanSansCN-Bold;
      color: #363b4c;
      margin-bottom: 12px;
    }

    .input-box {
      display: flex;

      .el-input__wrapper {
        background: #F5F6F7;
        border-radius: 4px;
        box-shadow: none;
      }

      .is-focus {
        box-shadow: 0 0 0 1px #1E6FFF !important;
      }

      .button {
        margin-left: 12px;
        width: 80px;
      }
    }
  }
}
</style>